﻿using MediatR;
using MES.Process.API.Application.Command.工序命令;
using MES.Process.API;
using MES.Process.Domain;
using MES.Process.ErrorCode;
using MES.Process.Infrastructure;
using Microsoft.EntityFrameworkCore;

namespace MES.Process.API.Application.CommandHandler.工序命令处理
{
    /// <summary>
    /// 所有工序集合
    /// </summary>
    public class ProcessQueryCommandHandler : IRequestHandler<ProcessQueryCommand, APIResult<List<Processes>>>
    {
        private readonly IBaseRepository<Processes> _processesRepository;
        private readonly ILogger<ProcessQueryCommandHandler> _logger;
        
        public ProcessQueryCommandHandler(IBaseRepository<Processes> processesRepository, ILogger<ProcessQueryCommandHandler> logger = null)
        {
            _processesRepository = processesRepository;
            _logger = logger;
        }

        public async Task<APIResult<List<Processes>>> Handle(ProcessQueryCommand request, CancellationToken cancellationToken)
        {
            try
            {
                APIResult<List<Processes>> result = new APIResult<List<Processes>>();
                var cacheKey = "Process:All";
                var cached = RedisUtil.Get<List<Processes>>(cacheKey);
                if (cached != null && cached.Count > 0)
                {
                    result.Code = APIEnums.Success;
                    result.Message = "查询成功";
                    result.Data = cached;
                    _logger?.LogInformation("工序集合命中缓存");
                    return result;
                }

                var list = await _processesRepository
                    .GetValues()
                    .OrderByDescending(x => x.CreateTime)
                    .ToListAsync(cancellationToken);

                RedisUtil.Set(cacheKey, list, TimeSpan.FromMinutes(10));

                result.Code = APIEnums.Success;
                result.Message = "查询成功";
                result.Data = list;
                _logger?.LogInformation("工序集合成功");
                return result;
            }
            catch (Exception ex)
            {

                throw;
            }
        }
    }
}
